package Asgmt1.element;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtil {
    public static void saveGameData(Player player){
        ObjectOutputStream oos;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("data\\"+player.getUsername()));
            oos.writeObject(player);
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static Player getGameData(String playerName){
        Player player = null;
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data\\"+playerName));
             player = (Player) ois.readObject();
            ois.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return player;
    }
    public static List<String> queryFileNames(){
        List<String> list = new ArrayList<>();
        File[] file = new File("data\\").listFiles();
        if (file == null){
            return list;
        }
        for (File value : file){
            String name = value.getName();
            list.add(name);
        }
        return list;
    }
    public static Map<String, Integer> getAllScores(){
        Map<String, Integer> allScores = new HashMap<>();
        List<String> playerNames = queryFileNames();
        for (String playerName : playerNames) {
            Player player = getGameData(playerName);
            int winNum = 0;
            List<Score> scores = player.getScores();
            for (Score score : scores) {
                if ("WIN".equals(score.getResult())){
                    winNum++;
                }
            }
            allScores.put(playerName,winNum);
        }
        return allScores;
    }
}
